package com.qf.shiro;


import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证成功后存储到session的对象
        DtsAdmin admin= (DtsAdmin) principalCollection.getPrimaryPrincipal();
        //获取该admin对应的角色id
        Integer[] roleIds = admin.getRoleIds();
        //根据角色id获取角色信息
        Set<String> roles = roleService.findRoleByIds(roleIds);
        //根据角色id获取权限信息
        Set<String> perms = permissionService.findPermByIds(roleIds);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }



    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户输入的账号和密码信息
        //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        //获取密码
       String password= new String((char[]) authenticationToken.getCredentials());

       //获取数据库中的该用户信息（根据用户名获取用户数据）
        DtsAdmin admin=adminService.findByUsername(username);
        //校验
        if (admin == null) {
            throw new UnknownAccountException("用户不存在");
        }
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if(admin.getPassword()==null||!passwordEncoder.matches(password,admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        if(admin.getDeleted()){
            throw new LockedAccountException("用户已锁定");
        }

        //参数1：用户对象 参数2：密码 参数3：真实姓名
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(admin,password,admin.getUsername());
        return authenticationInfo;
    }
}
